﻿using ELearning.BLL;
using ELearning.Common.Extensions;
using ELearning.Common.Model;
using ELearning.Models;
using ELearning.Models.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;

namespace ELearning.API.Controllers.AdminControllers
{
    [AllowAnonymous]
    public class DictionaryController : BaseApiController
    {
        protected EDictionaryService EDictionaryService = new EDictionaryService();
        /// <summary>
        /// 获取层级分明的菜单列表
        /// </summary>
        [HttpGet, Route("api/Dictionary/GetDictionary")]
        public ServiceResponse<List<DictionaryViewModel>> GetDictionary()
        {
            var ls = EDictionaryService.FindList(m => !m.IsDelete).OrderBy(w => w.ParentID).OrderBy(w => w.Sort).ToList();
            var viewModels = new List<DictionaryViewModel>();
            GetMenuViewModels(viewModels, ls, Guid.Parse("00000000-0000-0000-0000-000000000000"));
            return ServiceResponse<List<DictionaryViewModel>>.SuccessResponse("success", viewModels);
        }

        [HttpGet, Route("api/Dictionary/GetDictionaryIDByCode")]
        public ServiceResponse<Guid> GetDictionaryIDByCode(string code)
        {
            var subject = EDictionaryService.Find(w=>w.TypeCode==code);
            return ServiceResponse<Guid>.SuccessResponse("success", subject==null?new Guid(): subject.ID);
        }

        [HttpGet, Route("api/Dictionary/GetDictionaryIDByPCode")]
        public ServiceResponse<List<Guid>> GetDictionaryIDByPCode(string code)
        {
            var subjects = EDictionaryService.GetDicInParent(code);
            var guilist = subjects.Select(w => w.ID).ToList();
            return ServiceResponse<List<Guid>>.SuccessResponse("success", guilist);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("api/Dictionary/GetDictionaryByPCode")]
        public ServiceResponse<List<DictionaryViewModel>> GetDictionaryByPCode(string code)
        {
            var pdictionary = EDictionaryService.Find(w => w.TypeCode == code);
            //  var ls = EDictionaryService.FindList(m => !m.IsDelete&&m.ParentID==pdictionary.ID).ToList();
            // return ServiceResponse<List<EDictionary>>.SuccessResponse("success", ls);
            var ls = EDictionaryService.FindList(m => !m.IsDelete).OrderBy(w => w.ParentID).OrderBy(w => w.Sort).ToList();
            var viewModels = new List<DictionaryViewModel>();
            GetMenuViewModels(viewModels, ls, pdictionary.ID);
            return ServiceResponse<List<DictionaryViewModel>>.SuccessResponse("success", viewModels);
        }

        /// <summary>
        /// 获取所有字典项(未分层级)
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("api/Dictionary/GetAllDictionary")]
        public ServiceResponse<List<EDictionary>> GetAllDictionary()
        {
            var ls = EDictionaryService.FindList(m => !m.IsDelete).ToList();
            return ServiceResponse<List<EDictionary>>.SuccessResponse("success", ls);
        }

        /// <summary>
        /// 添加字典
        /// </summary>
        [HttpPost, Route("api/Dictionary/AddDic")]
        public ServiceResponse<EDictionary> AddDic(DictionaryViewModel viewModel)
        {
            var menu = new EDictionary
            {
                ID = Guid.NewGuid(),
                ParentID = viewModel.ParentID,
                TypeCode = viewModel.TypeCode,
                TypeName = viewModel.TypeName,
                IsDelete = false,
                Creater = CurrentUserModel.LoginName,
                CreateTime = DateTime.Now,
                Modifyer = CurrentUserModel.LoginName,
                ModifyTime = DateTime.Now,
                Sort = viewModel.Sort
            };

            if (menu.ParentID != new Guid())
            {
                var fullSpell = PinYinHelper.ConvertToAllSpell(menu.TypeName);//菜单全拼
                var firstSpell = PinYinHelper.GetFirstSpell(menu.TypeName);//菜单首拼
                var model = EDictionaryService.Find(m => !m.IsDelete && m.TypeCode.Equals(firstSpell, StringComparison.InvariantCultureIgnoreCase));
                if (model != null)
                {
                    model = EDictionaryService.Find(m => !m.IsDelete && m.TypeCode.Equals(fullSpell, StringComparison.InvariantCultureIgnoreCase));
                    if (model != null)
                    {
                        menu.TypeCode = $"{firstSpell}{DateTime.Now:yyMMddHHmmss}";
                    }
                    else
                    {
                        menu.TypeCode = fullSpell;
                    }
                }
                else
                {
                    menu.TypeCode = firstSpell;
                }
            }
            EDictionaryService.Add(menu);
            return ServiceResponse<EDictionary>.SuccessResponse("success", menu);
        }

        /// <summary>
        /// 更新字典
        /// </summary>
        [HttpPost, Route("api/Dictionary/UpdateDic")]
        public ServiceResponse<EDictionary> UpdateMenu(DictionaryViewModel viewModel)
        {
            var dic = EDictionaryService.Find(m => m.ID == viewModel.id);
            // dic.TypeCode=viewModel.TypeCode;
            dic.TypeName = viewModel.TypeName;
            dic.ParentID = viewModel.ParentID;
            dic.IsDelete = false;
            dic.Sort = viewModel.Sort;
            dic.ModifyTime = DateTime.Now;
            dic.Modifyer = CurrentUserModel.LoginName;
            EDictionaryService.Update(dic);
            return ServiceResponse<EDictionary>.SuccessResponse("success", dic);
        }

        /// <summary>
        /// 删除字典
        /// </summary>
        /// <param name="id">菜单id</param>
        [HttpGet, Route("api/Dictionary/DeleteDic")]
        public ServiceResponse<bool> DeleteDic(Guid id)
        {
            //var usedCount = EDictionaryService.GetDicUsedCount(id.ToString());
            //if (usedCount > 0) return ServiceResponse<bool>.SuccessResponse("删除失败：该类型已被使用，不可删除", false);

            var menu = EDictionaryService.Find(m => !m.IsDelete && m.ID == id);
            menu.IsDelete = true;
            menu.Modifyer = CurrentUserModel.LoginName;
            menu.ModifyTime = DateTime.Now;
            EDictionaryService.Update(menu);
            return ServiceResponse<bool>.SuccessResponse("success", true);
        }

        /// <summary>
        /// 构造层级菜单
        /// </summary>
        private void GetMenuViewModels(List<DictionaryViewModel> viewModels, List<EDictionary> models, Guid parentId)
        {
            var subList = models.Where(m => m.ParentID == parentId).OrderBy(w => w.ParentID).OrderBy(w => w.Sort).ToList();
            foreach (var menu in subList)
            {
                var viewModel = new DictionaryViewModel
                {
                    id = menu.ID,
                    ParentID = menu.ParentID,
                    ParentName = models.FirstOrDefault(w => w.ID == menu.ParentID)?.TypeName ?? "",
                    TypeCode = menu.TypeCode,
                    TypeName = menu.TypeName,
                    Sort = menu.Sort
                };
                GetMenuViewModels(viewModel.children, models, viewModel.id);
                if (!viewModel.children.Any())
                    viewModel.children = null;
                // viewModel.HasChildren = viewModel.Children==null?false: (viewModel.Children.Count > 0);
                viewModels.Add(viewModel);
            }
        }

        /// <summary>
        /// 检查字典code是否重复
        /// </summary>
        /// <param name="code">菜单id</param>
        [HttpGet, Route("api/Dictionary/existCode")]
        public ServiceResponse<bool> ExistCode(string code)
        {
            var exist = EDictionaryService.Find(x => x.TypeCode.Contains(code));
            if (exist != null) return ServiceResponse<bool>.SuccessResponse(false);
            else return ServiceResponse<bool>.SuccessResponse(true);
        }

        /// <summary>
        /// 获取指定code下面的字典列表，用于select展示使用
        /// </summary>
        /// <param name="code">类型编码</param>
        [HttpGet, Route("api/Dictionary/GetSelectDicByCode")]
        public ServiceResponse<SelectDicViewModel> GetSelectDicByCode(string code)
        {
            var pdictionary = EDictionaryService.Find(w => w.TypeCode == code);
            var modelList = EDictionaryService.FindList(m => !m.IsDelete).OrderBy(w => w.ParentID).OrderBy(w => w.Sort).ToList();
            var viewModel = new SelectDicViewModel();
            GenerateSelectList(modelList, viewModel.Items, pdictionary.ID);
            return ServiceResponse<SelectDicViewModel>.SuccessResponse(viewModel);
        }

        /// <summary>
        /// 构造全部等级列表，不包含children
        /// </summary>
        private void GenerateSelectList(List<EDictionary> modelList, List<SelectDicItem> viewModels, Guid pId, int i = 1)
        {
            i++;
            var subList = modelList.Where(l => !l.IsDelete && l.ParentID == pId).OrderBy(l => l.ParentID).ToList();
            foreach (var m in subList)
            {
                var str = "";
                //父级菜单不缩进  
                for (var j = 1; j < i; j++)
                {
                    str += HttpUtility.HtmlDecode("&nbsp;&nbsp;");
                }
                if (i > 2)
                    str += "├";
                var v = new SelectDicItem
                {
                    id = m.ID,
                    value = m.TypeCode,
                    label = $"{str}{m.TypeName}"
                };
                viewModels.Add(v);
                GenerateSelectList(modelList, viewModels, v.id, i);
            }
        }

    }
}